#include <Arduino.h>
#include <WiFi.h>
#include "PubSubClient.h"
#include <HTTPUpdate.h>
#include "esp_http_client.h"
#include "ArduinoJson.h"
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "driver/uart.h"
#include "string.h"
#include "driver/gpio.h"
#include <String>
#include <iostream>
#include "driver/i2c.h"
#include "driver/adc.h"

#include "config.hpp"
#include "Utils.hpp"

LightUtils utils;
//初始化任务句柄
TaskHandle_t Flag_Monitor_Handle;
TaskHandle_t Task_Display_Handle;


#include <ArduinoJson.h>

bool startPlay = false;
bool lastsetence = false;
bool isReady = false;
unsigned long urlTime = 0;

int noise = 50;
HTTPClient https;

hw_timer_t *timer = NULL;
uint8_t adc_start_flag = 0;
uint8_t adc_complete_flag = 0;

DynamicJsonDocument doc(4000);
JsonArray text = doc.to<JsonArray>();

String url = "";
String url1 = "";
String Date = "";

String askquestion = "";
String Answer = "";


void getTimeFromServer(void);



#define SHT31_I2C_ADDRESS 0x44               // SHT31的I2C地址
#define SHT31_CMD_MEASURE 0x2C06 // 启动测量命令
// static const char *TAG = "SHT31";

void i2c_master_init();
void sht31_read(float *temperature, float *humidity);

// 将电压转换为光强度（勒克斯）
float convertToLux(float voltage);


// 自动化任务 列表
StaticJsonDocument<1024*4> docauto;

// 自动化任务列表显示的flag
boolean combineAutoArrFlag = false;
// 自动化任务数量
int8_t demand_count = 0;
// 是否马上拉取自动化任务的flag
boolean getCombinemonitorFlag = false;


#include <string.h>
#define uint unsigned int

// delay for half a second
int delayval = 1000;

// 重启设备--阈值
int restartCount = 0;

void send_fotamsg(String fotastatus ,String toastmsg ,String progress);

// 重启设备flag标识
boolean esp_restartFlag = false;
// 是否自动上传的flag
boolean autoUploadFlag = false;

//fota的状态
int fota_status = 0;
boolean fotaFlag = false;
String updateurl= "";
String updateversion= "";
int totalProgress = -1;

// 定时器初始化
hw_timer_t *tim1 = NULL;
int tim1_IRQ_count = 0;

//全局的TCP连接，在发送UDP的时候，可以检测TCP获取的ID是否变化，以防服务端挂了后客户端不知道
WiFiClient client;
PubSubClient mqttclient(client);

// #include "esp_task_wdt.h"
// #define TWDT_TIMEOUT_S  30

//-----------网络时间获取-----------//
#define NTP1 "ntp1.aliyun.com"
#define NTP2 "ntp2.aliyun.com"
#define NTP3 "ntp3.aliyun.com"

//时区设置函数，东八区（UTC/GMT+8:00）写成8*3600
const long gmtOffset_sec = 8 * 3600;
const int daylightOffset_sec = 0;   //夏令时填写3600，否则填0

void reconnect();


// 连接WiFi网络
void wifiConnect(const char *wifiData[][2], int numNetworks)
{
    WiFi.disconnect(true);

    for (int i = 0; i < numNetworks; ++i)
    {
        const char *ssid = wifiData[i][0];
        const char *password = wifiData[i][1];

        Serial.print("Connecting to ");
        Serial.println(ssid);

        WiFi.begin(ssid, password);
        uint8_t count = 0;
        while (WiFi.status() != WL_CONNECTED)
        {
            Serial.print(".");
            count++;
            if (count >= 6)
            {
                Serial.printf("\r\n-- wifi connect fail! --\r\n");
                break;
            }
            vTaskDelay(500);
        }

        if (WiFi.status() == WL_CONNECTED)
        {
            Serial.printf("\r\n-- wifi connect success! --\r\n");
            Serial.print("IP address: ");
            Serial.println(WiFi.localIP());
            Serial.println("Free Heap: " + String(ESP.getFreeHeap()));
            return; // 如果连接成功，退出函数
        }
    }
}


// 当升级开始时，打印日志 fota_started/fota_progress/fota_finished/fota_error
void update_started() {
  totalProgress= -1;
  send_fotamsg("fota_started","升级开始","--");
  Serial.println("CALLBACK:  HTTP update process started");
}

// 当升级中，打印日志
void update_progress(int cur, int total) {
  float aa = (float)cur;
  float bb = (float)total;
    int grs = (int)(aa/bb *100);
    String progress = (String) grs ;

  if (  totalProgress != grs)
  {
    /* code */
        send_fotamsg("fota_progress","升级中",progress);

  }
      totalProgress = grs;


  Serial.printf("CALLBACK:  HTTP update process at %d of %d bytes...%s...%d... \n", cur, total,progress,grs);
}

// 当升级结束时，打印日志
void update_finished() {
  totalProgress= -1;
    send_fotamsg("fota_finished","升级完成","--");
  Serial.println("CALLBACK:  HTTP update process finished");
}

//当升级失败时，打印日志
void update_error(int err) {
  totalProgress= -1;
  send_fotamsg("fota_error","FOTA升级失败","--");
  Serial.printf("CALLBACK:  HTTP update fatal error code %d\n", err);
}

// 升级信息上报
void send_fotamsg(String fotastatus ,String toastmsg ,String progress){

    TimeStruct stc =  utils.setClock("");
    reporttime = stc.reporttime;
    String did = utils.md5str(reporttime +'0'+ random(1000));

    // 创建一个JSON文档
    DynamicJsonDocument doc(10240); // 分配足够的内存，根据实际数据大小调整
  
    // 设置顶层对象
    doc["did"] = did;
    doc["version"] = "1.0";
    // 创建params对象
    JsonObject params = doc.createNestedObject("params");
    // 获取北京时间和时间戳
    BeijingTimeResult result = utils.getBeijingTime();
    // 设置时间
    params["time"] = result.formattedTime.c_str();
    // 设置时间戳
    params["timestamp"] = result.timestampMs;
    JsonObject fota = params.createNestedObject("fota");
    fota["progress"] = progress;
    fota["fotastatus"] = fotastatus;
    fota["msg"] = toastmsg;

    DynamicJsonDocument docc(10240); // 分配足够的内存，根据实际数据大小调整

    // 生成JSON字符串
    String jsonString;
    serializeJsonPretty(docc, jsonString);

    // 生成并打印JSON数据
    String jsonData = jsonString;
    //   Serial.println(jsonData);
    StaticJsonDocument<1024> docs;
    deserializeJson(docs, jsonData);

    char  buffer[1024];
    size_t n = serializeJson(doc, buffer);
    Serial.println(buffer);

    if (mqttclient.publish( MQTT_PUB_OTA_POST.c_str(),buffer,n)) {
    //   Serial.printf("auto topic [%s] ok\n",  MQTT_PUB_PROPERTY_POST);
    } else {
        Serial.printf("auto topic [%s] fail\n",  MQTT_PUB_OTA_POST);
       
    }

}

// 设备升级更新检测
void updateDevice(String upUrl,String updateversion){

    String ver = (String)version;
    String newver = (String)updateversion;
    Serial.println(ver);
    Serial.println(newver);
    Serial.println("----------------------");

    Serial.println(upUrl);
    Serial.println(updateversion);

    if (ver == newver)
    {
        Serial.println("version equal ");

        //FOTA开始的通知 mqtt 小程序提示
        send_fotamsg("fota_checked","已是最新版本","--");
        return ;
    }
    else if ( upUrl == ""){

       //FOTA开始的通知 mqtt 小程序提示
        send_fotamsg("fota_error","FOTA升级地址错误","--");

        Serial.println("url error");
        return ;
    }
    //FOTA开始的通知 mqtt 小程序提示
    String toast = "";

    Serial.println("start update");
    WiFiClient UpdateClient = client;

    //如果是旧版esp32 SDK，需要删除下面四行，旧版不支持，不然会报错
    httpUpdate.onStart(update_started);//当升级开始时
    httpUpdate.onEnd(update_finished);//当升级结束时
    httpUpdate.onProgress(update_progress);//当升级中
    httpUpdate.onError(update_error);//当升级失败时

    t_httpUpdate_return ret = httpUpdate.update(UpdateClient, upUrl);
    switch(ret) {
        case HTTP_UPDATE_FAILED:      //当升级失败
            toast = "FOTA升级失败";
            Serial.println("[update] Update failed.");
            break;
        case HTTP_UPDATE_NO_UPDATES:  //当无升级
            toast = "无FOTA升级";
            Serial.println("[update] Update no Update.");
            break;
        case HTTP_UPDATE_OK:         //当升级成功
            toast = "FOTA升级成功";
            Serial.println("[update] Update ok.");
            break;
    }
}

// led alarm初始化
void cmd_GPIO_Init(){
    //设置io口为输出模式

    pinMode(alarm,OUTPUT);
    digitalWrite(alarm, LOW);

    pinMode(rc1,OUTPUT);
    digitalWrite(rc1, LOW);

    pinMode(rc2,OUTPUT);
    digitalWrite(rc2, LOW);

    pinMode(rc3,OUTPUT);
    digitalWrite(rc3, LOW);

    pinMode(rc4,OUTPUT);
    digitalWrite(rc4, HIGH);

    //设置io口为输出模式

}

// 发送设备状态数据
String createPubPropertyData() {

    unsigned char rc1_status = digitalRead(rc1) ;
    unsigned char rc2_status = digitalRead(rc2) ;
    unsigned char rc3_status = digitalRead(rc3) ;
    unsigned char rc4_status = digitalRead(rc4) ;
    unsigned char alarm_status = digitalRead(alarm) ;

    TimeStruct stc =  utils.setClock("");
    reporttime = stc.reporttime;
    String did = utils.md5str(reporttime +'0'+ random(1000));

    // 创建一个JSON文档
    DynamicJsonDocument doc(10240); // 分配足够的内存，根据实际数据大小调整
  
    // 设置顶层对象
    doc["did"] = did;
    doc["version"] = "1.0";
  
    // 创建params对象
    JsonObject params = doc.createNestedObject("params");


    // 获取北京时间和时间戳
    BeijingTimeResult result = utils.getBeijingTime();
        

    // 设置时间
    params["time"] = result.formattedTime.c_str();
    
    // 设置时间戳
    params["timestamp"] = result.timestampMs;
  
    // 创建functions数组
    JsonArray functions = params.createNestedArray("functions");
    

    // 添加functions元素
    {
        JsonObject func1 = functions.createNestedObject();
        func1["id"] = "lamp_livingroom";
        func1["value"] = lamp_livingroom ? "open" : "close";
        func1["remark"] = "客厅灯";
    }

    {
        JsonObject func2 = functions.createNestedObject();
        func2["id"] = "lamp_kitchen";
        func2["value"] = lamp_kitchen ? "open" : "close";
        func2["remark"] = "厨房灯";
    }

    {
        JsonObject func3 = functions.createNestedObject();
        func3["id"] = "lamp_bedroom";
        func3["value"] = lamp_bedroom ? "open" : "close";
        func3["remark"] = "卧室灯";
    }

    // 补充剩余设备的JSON配置
    {
        JsonObject func4 = functions.createNestedObject();
        func4["id"] = "lamp_bathroom";
        func4["value"] = lamp_bathroom ? "open" : "close";
        func4["remark"] = "洗手间灯";
    }

    {
        JsonObject func5 = functions.createNestedObject();
        func5["id"] = "lamp_diningroom";
        func5["value"] = lamp_diningroom ? "open" : "close";
        func5["remark"] = "餐厅灯";
    }

    {
        JsonObject func6 = functions.createNestedObject();
        func6["id"] = "lamp_studyroom";
        func6["value"] = lamp_studyroom ? "open" : "close";
        func6["remark"] = "书房灯";
    }

    {
        JsonObject func7 = functions.createNestedObject();
        func7["id"] = "fan_livingroom";
        func7["value"] = fan_livingroom ? "open" : "close";
        func7["remark"] = "客厅风扇";
    }

    {
        JsonObject func8 = functions.createNestedObject();
        func8["id"] = "ac_livingroom";
        func8["value"] = ac_livingroom ? "open" : "close";
        func8["remark"] = "客厅空调";
    }

    {
        JsonObject func9 = functions.createNestedObject();
        func9["id"] = "alarm_livingroom";
        func9["value"] = alarm_livingroom ? "open" : "close";
        func9["remark"] = "客厅告警";
    }

    {
        JsonObject func10 = functions.createNestedObject();
        func10["id"] = "tablelamp_bedroom";
        func10["value"] = tablelamp_bedroom ? "open" : "close";
        func10["remark"] = "卧室台灯";
    }

    {
        JsonObject func11 = functions.createNestedObject();
        func11["id"] = "closetlamp_bedroom";
        func11["value"] = closetlamp_bedroom ? "open" : "close";
        func11["remark"] = "卧室衣柜灯";
    }

    {
        JsonObject func12 = functions.createNestedObject();
        func12["id"] = "domelamp_livingroom";
        func12["value"] = domelamp_livingroom ? "open" : "close";
        func12["remark"] = "客厅顶灯";
    }

    {
        JsonObject func13 = functions.createNestedObject();
        func13["id"] = "porchlamp_livingroom";
        func13["value"] = porchlamp_livingroom ? "open" : "close";
        func13["remark"] = "客厅玄关灯";
    }

    {
        JsonObject func15 = functions.createNestedObject();
        func15["id"] = "tv_livingroom";
        func15["value"] = tv_livingroom ? "open" : "close";
        func15["remark"] = "客厅电视";
    }

    {
        JsonObject func16 = functions.createNestedObject();
        func16["id"] = "curtain_livingroom";
        func16["value"] = curtain_livingroom ? "open" : "close";
        func16["remark"] = "客厅窗帘";
    }



    // 创建properties数组
    JsonArray properties = params.createNestedArray("properties");
  
    // 添加properties元素
    {
        JsonObject prop1 = properties.createNestedObject();
        prop1["id"] = "temperature";
        prop1["value"] = old_sht31_temp;
        prop1["remark"] = "温度";
    }
    
    {
        JsonObject prop2 = properties.createNestedObject();
        prop2["id"] = "humidity";
        prop2["value"] = old_sht31_humi;
        prop2["remark"] = "湿度";
    }
    
    {
        JsonObject prop3 = properties.createNestedObject();
        prop3["id"] = "lux";
        prop3["value"] = old_lux;
        prop3["remark"] = "光照强度";
    }

    {
        JsonObject prop4 = properties.createNestedObject();
        prop4["id"] = "person";
        prop4["value"] = person;
        prop4["remark"] = "人员检测";
    }

    {
        JsonObject prop5 = properties.createNestedObject();
        prop5["id"] = "flame";
        prop5["value"] = flame;
        prop5["remark"] = "火焰检测";
    }

    {
        JsonObject prop6 = properties.createNestedObject();
        prop6["id"] = "tvoc";
        prop6["value"] = tvoc;
        prop6["remark"] = "总挥发性有机物";
    }

    {
        JsonObject prop7 = properties.createNestedObject();
        prop7["id"] = "co2";
        prop7["value"] = co2;
        prop7["remark"] = "二氧化碳";
    }

    {
        JsonObject prop8 = properties.createNestedObject();
        prop8["id"] = "formaldehyde";
        prop8["value"] = formaldehyde;
        prop8["remark"] = "甲醛";
    }


    // 生成JSON字符串
    String jsonString;
    serializeJsonPretty(doc, jsonString);
  
    return jsonString;
}

// 10s自动上报数据
void pubProperty(){
     // 生成并打印JSON数据
  String jsonData = createPubPropertyData();
//   Serial.println(jsonData);
  StaticJsonDocument<2028> doc;
  deserializeJson(doc, jsonData);

  char  buffer[2028];
  size_t n = serializeJson(doc, buffer);


//   Serial.println(buffer);

  if (mqttclient.publish( MQTT_PUB_PROPERTY_POST.c_str(),buffer,n)) {
    //   Serial.printf("auto topic [%s] ok\n",  MQTT_PUB_PROPERTY_POST);
      restartCount = 0;

  } else {
      Serial.printf("auto topic [%s] fail\n",  MQTT_PUB_PROPERTY_POST);
      restartCount++;

      //三次错误，就直接重启设备
      if (restartCount >=3)
      {
          // alarmLevel = 3;
          restartCount = 0;
          Serial.printf("restarxxx3");
          // esp_restartFlag = true;//继续联网别重启
      }
  }

}
// 发送设备状态数据
String createPubInfoData() {

    
    unsigned char rc1_status = digitalRead(rc1) ;
    unsigned char rc2_status = digitalRead(rc2) ;
    unsigned char rc3_status = digitalRead(rc3) ;
    unsigned char rc4_status = digitalRead(rc4) ;
    unsigned char alarm_status = digitalRead(alarm) ;

    TimeStruct stc =  utils.setClock("");
    reporttime = stc.reporttime;
    String did = utils.md5str(reporttime +'0'+ random(1000));

    // 创建一个JSON文档
    DynamicJsonDocument doc(1024); // 分配足够的内存，根据实际数据大小调整
  
    // 设置顶层对象
    doc["did"] = did;
    doc["version"] = "1.0";
  
    // 创建params对象
    JsonObject params = doc.createNestedObject("params");


    // 获取北京时间和时间戳
    BeijingTimeResult result = utils.getBeijingTime();
        

    // 设置时间
    params["time"] = result.formattedTime.c_str();
    
    // 设置时间戳
    params["timestamp"] = result.timestampMs;


    JsonObject info = params.createNestedObject("info");

    info["longitude"] = 0;
    info["userId"] = 1;
    info["rssi"] = 0;
    info["fversion"] = "V1";
    info["version_name"] = version;
    info["status"] = 3;
    info["latitude"] = 0;
    info["chip"] = "ESP32S3";

    // 创建summary
    JsonObject summary = info.createNestedObject("summary");
  
    summary["name"] = "device";
    summary["author"] = "silizap";
    summary["create"] = "2025-05-18";
    summary["product"] = "AISH";
    summary["upload_time"] = 10000;

  
    // 生成JSON字符串
    String jsonString;
    serializeJsonPretty(doc, jsonString);
  
    return jsonString;
}

// 开启自动上报
void pubInfoData(){

    // 生成并打印JSON数据
    String jsonData = createPubInfoData();
    //   Serial.println(jsonData);
    StaticJsonDocument<1024> doc;
    deserializeJson(doc, jsonData);

    char  buffer[1024];
    size_t n = serializeJson(doc, buffer);


    Serial.println(buffer);

    if (mqttclient.publish( MQTT_PUB_INFO_POST.c_str(),buffer,n)) {
    //   Serial.printf("auto topic [%s] ok\n",  MQTT_PUB_PROPERTY_POST);
        restartCount = 0;

    } else {
        Serial.printf("auto topic [%s] fail\n",  MQTT_PUB_PROPERTY_POST);
        restartCount++;

        //三次错误，就直接重启设备
        if (restartCount >=3)
        {
            // alarmLevel = 3;
            restartCount = 0;
            Serial.printf("restarxxx3");
            // esp_restartFlag = true;//继续联网别重启
        }
    }

}

// 中断服务函数
void tim1Interrupt()
{
    timerAlarmEnabled(tim1);
    autoUploadFlag = true;
}

// 定时器初始化
void timerInit(){
  tim1 = timerBegin(0, 80, true);
  timerAttachInterrupt(tim1, tim1Interrupt, true);
  timerAlarmWrite(tim1, 10000000ul, true);  //10s 10000000ul
  timerAlarmEnable(tim1);

}

// 平台下发的远控指令-回调
void callback(char* topic, byte* payload, unsigned int length)
{
    Serial.println(topic);

    //json数据解析
    StaticJsonDocument<1024*6> doc;
    DeserializationError error = deserializeJson(doc, payload, length);

    if (error) {
      Serial.print(F("deserializeJson() failed: "));
      Serial.println(error.c_str());
    }
    // Serial.println();
    serializeJsonPretty(doc, Serial);
    Serial.println("------------------");

    if (strcmp(topic, MQTT_SUB_FUNCTION_GET.c_str()) == 0)
    {
        // 获取设备ID和版本号
        const char* did = doc["did"] | "";
        const char* version = doc["version"] | "";
        
        Serial.print("did: ");
        Serial.println(did);
        Serial.print("Version: ");
        Serial.println(version);
        
        // 获取参数数组
        JsonArray params = doc["params"];
        
        // 遍历参数数组
        for (JsonObject param : params) {
            const char* sensorname = param["sensorname"] | "";
            const char* sensorcmd = param["sensorcmd"] | "";
            JsonObject extdata = param["extdata"];
            
            Serial.print("Sensor Name: ");
            Serial.println(sensorname);
            Serial.print("Sensor Command: ");
            Serial.println(sensorcmd);
            
            // 处理不同的传感器命令
            if (strcmp(sensorname, "status") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Handling status open command");
                    // 基础数据查询
                    // pubProperty();
                }
            }
            else if (strcmp(sensorname, "restart") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Handling restart command");
                    // 延时重启，避免立即重启导致通信中断
                    delay(300);
                    ESP.restart();
                }
            }
            else if (strcmp(sensorname, "poweroff") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Handling poweroff command");
                    // 延时关机，避免立即关机导致通信中断
                    delay(300);
                    // ESP32没有直接关机的函数，这里可以进入深度睡眠
                    esp_deep_sleep_start();
                }
            }
            else if (strcmp(sensorname, "alarm_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening alarm_livingroom");
                    // digitalWrite(alarm,HIGH);
                    alarm_livingroom = 1;
                    autoUploadFlag = true;
                }
                else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing alarm_livingroom");
                    // digitalWrite(alarm,LOW);
                    alarm_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "fan_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening fan_livingroom");
                    // digitalWrite(rc4,LOW);
                    fan_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing fan_livingroom");
                    // digitalWrite(rc4,HIGH);
                    fan_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "lamp_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening lamp_livingroom");
                    // digitalWrite(livingroom_light, HIGH);  // 根据实际引脚修改
                    lamp_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing lamp_livingroom");
                    // digitalWrite(livingroom_light, LOW);   // 根据实际引脚修改
                    lamp_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "lamp_kitchen") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening lamp_kitchen");
                    // digitalWrite(kitchen_light, HIGH);     // 根据实际引脚修改
                    lamp_kitchen = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing lamp_kitchen");
                    // digitalWrite(kitchen_light, LOW);      // 根据实际引脚修改
                    lamp_kitchen = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "lamp_bedroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening lamp_bedroom");
                    // digitalWrite(bedroom_light, HIGH);     // 根据实际引脚修改
                    lamp_bedroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing lamp_bedroom");
                    // digitalWrite(bedroom_light, LOW);      // 根据实际引脚修改
                    lamp_bedroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "lamp_bathroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening lamp_bathroom");
                    // digitalWrite(bathroom_light, HIGH);    // 根据实际引脚修改
                    lamp_bathroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing lamp_bathroom");
                    // digitalWrite(bathroom_light, LOW);     // 根据实际引脚修改
                    lamp_bathroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "lamp_diningroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening lamp_diningroom");
                    // digitalWrite(diningroom_light, HIGH);  // 根据实际引脚修改
                    lamp_diningroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing lamp_diningroom");
                    // digitalWrite(diningroom_light, LOW);   // 根据实际引脚修改
                    lamp_diningroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "lamp_studyroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening lamp_studyroom");
                    // digitalWrite(studyroom_light, HIGH);   // 根据实际引脚修改
                    lamp_studyroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing lamp_studyroom");
                    // digitalWrite(studyroom_light, LOW);    // 根据实际引脚修改
                    lamp_studyroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "ac_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening ac_livingroom");
                    // digitalWrite(air_conditioner, HIGH);   // 根据实际引脚修改
                    ac_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing ac_livingroom");
                    // digitalWrite(air_conditioner, LOW);    // 根据实际引脚修改
                    ac_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "tablelamp_bedroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening tablelamp_bedroom");
                    // digitalWrite(tablelamp_bedroom_pin, HIGH);   // 根据实际引脚修改
                    tablelamp_bedroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing tablelamp_bedroom");
                    // digitalWrite(tablelamp_bedroom_pin, LOW);    // 根据实际引脚修改
                    tablelamp_bedroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "closetlamp_bedroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening closetlamp_bedroom");
                    // digitalWrite(closetlamp_bedroom_pin, HIGH);   // 根据实际引脚修改
                    closetlamp_bedroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing closetlamp_bedroom");
                    // digitalWrite(closetlamp_bedroom_pin, LOW);    // 根据实际引脚修改
                    closetlamp_bedroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "domelamp_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening domelamp_livingroom");
                    // digitalWrite(domelamp_livingroom_pin, HIGH);   // 根据实际引脚修改
                    domelamp_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing domelamp_livingroom");
                    // digitalWrite(domelamp_livingroom_pin, LOW);    // 根据实际引脚修改
                    domelamp_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "porchlamp_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening porchlamp_livingroom");
                    // digitalWrite(porchlamp_livingroom_pin, HIGH);   // 根据实际引脚修改
                    porchlamp_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing porchlamp_livingroom");
                    // digitalWrite(porchlamp_livingroom_pin, LOW);    // 根据实际引脚修改
                    porchlamp_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "tablelamp_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening tablelamp_livingroom");
                    // digitalWrite(tablelamp_livingroom_pin, HIGH);   // 根据实际引脚修改
                    tablelamp_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing tablelamp_livingroom");
                    // digitalWrite(tablelamp_livingroom_pin, LOW);    // 根据实际引脚修改
                    tablelamp_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "tv_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening tv_livingroom");
                    // digitalWrite(tv_livingroom_pin, HIGH);   // 根据实际引脚修改
                    tv_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing tv_livingroom");
                    // digitalWrite(tv_livingroom_pin, LOW);    // 根据实际引脚修改
                    tv_livingroom = 0;
                    autoUploadFlag = true;
                }
            } else if (strcmp(sensorname, "curtain_livingroom") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Opening curtain_livingroom");
                    // digitalWrite(curtain_livingroom_open_pin, HIGH);   // 根据实际引脚修改
                    // digitalWrite(curtain_livingroom_close_pin, LOW);
                    curtain_livingroom = 1;
                    autoUploadFlag = true;
                } else if (strcmp(sensorcmd, "close") == 0) {
                    Serial.println("Closing curtain_livingroom");
                    // digitalWrite(curtain_livingroom_open_pin, LOW);    // 根据实际引脚修改
                    // digitalWrite(curtain_livingroom_close_pin, HIGH);
                    curtain_livingroom = 0;
                    autoUploadFlag = true;
                }
            }
            else if (strcmp(sensorname, "ota") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Handling OTA update");
                    
                    String updateurlcc = extdata["url"] | "";
                    updateurl = updateurlcc;

                    String updateversionCC = extdata["version"] | "";
                    updateversion = updateversionCC;
                    
                    Serial.print("Update URL: ");
                    Serial.println(updateurl);
                    Serial.print("Update Version: ");
                    Serial.println(updateversion);
                    
                    if (strlen(updateurl.c_str()) > 0) {
                        Serial.println("Starting OTA update from URL");
                        // 启动OTA更新
                        fotaFlag = true;

                    } else {
                        Serial.println("Invalid update URL");
                    }
                }
            }
           
        
        // 构造响应消息
        DynamicJsonDocument responseDoc(1024);
        responseDoc["did"] = did;
        responseDoc["version"] = "1.0";
        responseDoc["code"] = 200;
        responseDoc["msg"] = "";
        
        JsonObject paramsObj = responseDoc.createNestedObject("params");
        
        // 获取当前时间
        time_t now;
        struct tm timeinfo;
        time(&now);
        localtime_r(&now, &timeinfo);
        
        char timeStringBuff[26];
        strftime(timeStringBuff, sizeof(timeStringBuff), "%Y-%m-%d %H:%M:%S", &timeinfo);
        paramsObj["time"] = timeStringBuff;
        
        // 获取毫秒级时间戳
        uint32_t timestamp = millis();
        paramsObj["timestamp"] = timestamp;
        
        // 复制原始命令参数到响应中
        paramsObj["functions"] = params;
        
        // 序列化为JSON字符串
        // char responseBuffer[1024];
        // serializeJson(responseDoc, responseBuffer);
        
        // 发送响应
        // mqttclient.publish(MQTT_PUB_FUNCTION_GET_REPLY, responseBuffer);
        // Serial.println("Response:");
        // Serial.println(responseBuffer);


        char  buffer[1024];
        size_t n = serializeJson(responseDoc, buffer);

        if (mqttclient.publish( MQTT_PUB_FUNCTION_GET_REPLY.c_str(), buffer,n)) {
            // Serial.printf("auto topic ack [%s] ok\n",  MQTT_PUB_FUNCTION_GET_REPLY);

        } else {
            Serial.printf("auto topic ack [%s] fail\n",  MQTT_PUB_FUNCTION_GET_REPLY);
        }

        }

    }else if (strcmp(topic, MQTT_SUB_OTA_GET.c_str()) == 0)
    {
        // 获取设备ID和版本号
        const char* did = doc["did"] | "";
        const char* version = doc["version"] | "";
        
        Serial.print("did: ");
        Serial.println(did);
        Serial.print("Version: ");
        Serial.println(version);
        
        // 获取参数数组
        JsonArray params = doc["params"];
        
        // 遍历参数数组
        for (JsonObject param : params) {
            const char* sensorname = param["sensorname"] | "";
            const char* sensorcmd = param["sensorcmd"] | "";
            JsonObject extdata = param["extdata"];
            
            Serial.print("Sensor Name: ");
            Serial.println(sensorname);
            Serial.print("Sensor Command: ");
            Serial.println(sensorcmd);
            
            // 处理不同的传感器命令
            if (strcmp(sensorname, "ota") == 0) {
                if (strcmp(sensorcmd, "open") == 0) {
                    Serial.println("Handling OTA update");
                    
                    String updateurlcc = extdata["url"] | "";
                    updateurl = updateurlcc;

                    String updateversionCC = extdata["version"] | "";
                    updateversion = updateversionCC;
                    
                    Serial.print("Update URL: ");
                    Serial.println(updateurl);
                    Serial.print("Update Version: ");
                    Serial.println(updateversion);
                    
                    if (strlen(updateurl.c_str()) > 0) {
                        Serial.println("Starting OTA update from URL");
                        // 启动OTA更新
                        fotaFlag = true;

                    } else {
                        Serial.println("Invalid update URL");
                    }
                }
            }
        
        // 构造响应消息
        DynamicJsonDocument responseDoc(1024);
        responseDoc["did"] = did;
        responseDoc["version"] = "1.0";
        responseDoc["code"] = 200;
        responseDoc["msg"] = "";
        
        JsonObject paramsObj = responseDoc.createNestedObject("params");
        
        // 获取当前时间
        time_t now;
        struct tm timeinfo;
        time(&now);
        localtime_r(&now, &timeinfo);
        
        char timeStringBuff[26];
        strftime(timeStringBuff, sizeof(timeStringBuff), "%Y-%m-%d %H:%M:%S", &timeinfo);
        paramsObj["time"] = timeStringBuff;
        
        // 获取毫秒级时间戳
        uint32_t timestamp = millis();
        paramsObj["timestamp"] = timestamp;
        
        // 复制原始命令参数到响应中
        paramsObj["functions"] = params;


        char  buffer[1024];
        size_t n = serializeJson(responseDoc, buffer);

        if (mqttclient.publish( MQTT_PUB_OTA_GET_REPLY.c_str(), buffer,n)) {
            // Serial.printf("auto topic ack [%s] ok\n",  MQTT_PUB_FUNCTION_GET_REPLY);

        } else {
            Serial.printf("auto topic ack [%s] fail\n",  MQTT_PUB_OTA_GET_REPLY);
        }

        }

    }else if (strcmp(topic, MQTT_SUB_MONITOR_GET.c_str()) == 0){
        // 创建一个子线程来处理combinecontroll命令
        //  -- 一键下发
        // 获取设备ID和版本号
        const char* did = doc["did"] | "";
        const char* version = doc["version"] | "";
        
        Serial.print("did: ");
        Serial.println(did);
        Serial.print("Version: ");
        Serial.println(version);
        
        // 获取参数数组
        JsonArray params = doc["params"];

        // {"version":"1.0","params":[{"sensorname":"combinecontroll","sensorcmd":"open","extdata":{"data":[{"cmddata":{"sensor":"lamp_bedroom","sensorname":"卧室灯","sensorcmd":"open","notes":"打开","extdata":{}},"cmdname":"卧室灯：打开","cmdtype":"exe_controll"},{"cmddata":{"timevalue":1000},"cmdname":"","cmdtype":"exe_delay"},{"cmddata":{"sensor":"lamp_bedroom","sensorname":"卧室灯","sensorcmd":"close","notes":"打开","extdata":{}},"cmdname":"卧室灯：打开","cmdtype":"exe_controll"}]}}],"did":"3N0OKKPIOXBTLxG79yDx5ioZdXyYqnoj"}

        for (JsonObject param : params) {
            const char* sensorname = param["sensorname"] | "";
            const char* sensorcmd = param["sensorcmd"] | "";
            JsonObject extdata = param["extdata"];
            
            Serial.print("Sensor Name: ");
            Serial.println(sensorname);
            Serial.print("Sensor Command: ");
            Serial.println(sensorcmd);

            if (strcmp(sensorname, "deviceconfig") == 0)
            {
                /* code */
                // 设备配置
                // {"sensorname":"deviceconfig","sensorcmd":"open","extdata":{"device_model":1,"interval":10000,"deeprest_interval":600000,"cmd_ext":0,"uuid":""}}
                // 设备模型
                int device_model = extdata["device_model"];
                // 上报间隔
                int interval = extdata["interval"];
                // 深睡间隔
                int deeprest_interval = extdata["deeprest_interval"];
                // 命令扩展
                int cmd_ext = extdata["cmd_ext"];
                // 设备UUID
                String uuid = extdata["uuid"];

            }else if (strcmp(sensorname, "monitor") == 0)
            {
                /* code */

            }else {

            }
            
            


        }   


    }
}



// void wdt_init(){
//     rtc_wdt_protect_off();     //看门狗写保护关闭 关闭后可以喂狗
//     //rtc_wdt_protect_on();    //看门狗写保护打开 打开后不能喂狗
//     //rtc_wdt_disable();       //禁用看门狗
//     rtc_wdt_enable();          //启用看门狗
//     rtc_wdt_set_time(RTC_WDT_STAGE0, 30000); // 设置看门狗超时 8000ms.则reset重启
// }

#include <esp32-hal.h>
#include <lwip/apps/sntp.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>

/**
 * @brief 设置时区和NTP服务器和并校对时间
 * @param [in] posix_tz 表示posix规范的时间戳。例如"UTC-8"表示东八区（北京时间）
 * @param [in] server_cnt NTP服务器的数量，超过三个的会被抛弃
 * @param [in] ... NTP服务器，C风格字符串指针类型，数量应与server_cnt对应
 * @attention 函数不会保证WiFi连接正常
 * @example set_time("UTC-8", 3, "time2.cloud.tencent.com", "ntp1.aliyun.com", "ntp.ntsc.ac.cn");
 * @example set_time("UTC+6", 2, "time2.cloud.tencent.com", "192.168.0.2");
 */
void set_time(const char *const posix_tz, const int server_cnt,const char* server1, const char* server2, const char* server3)
{
	sntp_setoperatingmode(SNTP_OPMODE_POLL);

    sntp_setservername(0, (char*)server1);
    sntp_setservername(1, (char*)server2);
    sntp_setservername(2, (char*)server3);

	sntp_init();
	setenv("TZ", posix_tz, 1);
	tzset();
	while (time(NULL) < 1580000000) // 阻塞，直到时间同步
		yield();
	sntp_stop();
}


void FlagMonitor(void *param)
{
    while (true)
    {
        vTaskDelay(10/portTICK_PERIOD_MS);
        if (!mqttclient.connected()) {
            //断网重来开始
            Serial.println("do loop 断网重连开始");
            reconnect();
        }
        // client loop
        mqttclient.loop();
        // Serial.print("loop running");
        // Serial.println(xPortGetCoreID());

        // 是否FOTA
        if (fotaFlag)
        {
            fotaFlag = false;
            updateDevice(updateurl,updateversion);
        }

        // 是否上报设备状态 10s中断上报
        if (autoUploadFlag)
        {
            autoUploadFlag = false;
            pubProperty();
        }

        if (esp_restartFlag)
        {
            esp_restartFlag = false;
            mqttclient.disconnect();
            delay(200);
            esp_restart();
        }

    }
}


// 初始化MQTT主题
void initMQTTTopics() {
    // 清空原有订阅主题数组
    subTopicsArr.clear();
    
    // 生成订阅主题
    MQTT_SUB_MONITOR_GET = "$sys/" + product_id + "/" + MAC + "/silizap/monitor/get";
    MQTT_SUB_FUNCTION_GET = "$sys/" + product_id + "/" + MAC + "/silizap/function/get";
    MQTT_SUB_OTA_GET = "$sys/" + product_id + "/" + MAC + "/silizap/ota/get";
    
    // 将订阅主题添加到数组
    subTopicsArr.push_back(MQTT_SUB_MONITOR_GET);
    subTopicsArr.push_back(MQTT_SUB_FUNCTION_GET);
    subTopicsArr.push_back(MQTT_SUB_OTA_GET);

    MQTT_PUB_INFO_POST = "$sys/" + product_id + "/" + MAC + "/silizap/info/post";
    MQTT_PUB_MONITOR_GET_REPLY = "$sys/" + product_id + "/" + MAC + "/silizap/monitor/get_reply";
    MQTT_PUB_MONITOR_POST = "$sys/" + product_id + "/" + MAC + "/silizap/monitor/post";
    MQTT_PUB_FUNCTION_GET_REPLY = "$sys/" + product_id + "/" + MAC + "/silizap/function/get_reply";
    MQTT_PUB_OTA_POST = "$sys/" + product_id + "/" + MAC + "/silizap/ota/post";
    MQTT_PUB_OTA_GET_REPLY = "$sys/" + product_id + "/" + MAC + "/silizap/ota/get_reply";
    MQTT_PUB_PROPERTY_POST = "$sys/" + product_id + "/" + MAC + "/silizap/property/post";
    MQTT_PUB_EVENT_POST = "$sys/" + product_id + "/" + MAC + "/silizap/event/post";
    
    mqtt_mqttClientId = "S&" + MAC + "&" + product_id + "&" + user_id ;
}

void setup() {
   
    // setCpuFrequencyMhz(240);//将ESP32主频设置为240MHz，最高主频运行

    Serial.begin(115200);
    Serial.setDebugOutput(true);
    while (!Serial) {
        /* code */
    }

    cmd_GPIO_Init();
    // ESP_ERROR_CHECK(i2c_master_init());//iIC初始化
    i2c_master_init();


    // utils.setup_wifi(ssid, passwd);
    int numNetworks = sizeof(wifiData) / sizeof(wifiData[0]);
    utils.setup_wifi(wifiData, numNetworks);

    configTime(8 * 3600, 0, NTP1, NTP2, NTP3);

    // set_time("UTC-8", 3, "time2.cloud.tencent.com", "ntp1.aliyun.com", "ntp.ntsc.ac.cn");

    MAC = utils.getmac();
    initMQTTTopics();

    // connect mqtt server
    mqttclient.setServer(mqtt_mqttHostUrl.c_str(), mqtt_port);
    mqttclient.setCallback(callback);
    mqttclient.setKeepAlive(60);
    while (!mqttclient.connect(mqtt_mqttClientId.c_str(), mqtt_username.c_str(), mqtt_passwd.c_str())) {
        Serial.println("mqtt connect fail, reconnect");

        int numNetworks = sizeof(wifiData) / sizeof(wifiData[0]);
        utils.setup_wifi(wifiData, numNetworks);

    }

    Serial.println("mqtt connected!");

    // sub topic
    
    for ( String topic : subTopicsArr) {
        boolean ret = mqttclient.subscribe(topic.c_str());
        if (ret != true) {
            Serial.printf("mqtt subscribe topic [%s] fail\n",topic );
        }
        Serial.printf("mqtt subscribe topic [%s] ok\n", topic);
    
    }

 
    // wdt_init();
    // Serial.printf("wdt_init\n");

    //定时器
    timerInit();

    getTimeFromServer();

     urlTime = millis();
    

     xTaskCreatePinnedToCore(
        FlagMonitor       // 这个任务运行的函数
        ,  "Flag Monitor" // 给人看的名字
        ,  10*1024        // 任务栈的大小，用于存储任务运行时的上下文信息。简单来说，就是最多存这么多信息
        ,  NULL           // 任务参数。要么没有填NULL；要么必须为无类型指针
        ,  3             // 优先级
        ,  &Flag_Monitor_Handle // 任务的句柄，用于管理和控制任务
        ,  0              // 指定任务分配的核心
    );

    // 发送设备在线topic
    pubInfoData();

}

void reconnect() {

    while (!mqttclient.connected()) {

        // 重新打开wifi链接、
        Serial.println("reset wifi ...");

        int numNetworks = sizeof(wifiData) / sizeof(wifiData[0]);
        utils.setup_wifi(wifiData, numNetworks);


        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (mqttclient.connect(mqtt_mqttClientId.c_str(), mqtt_username.c_str(), mqtt_passwd.c_str())) {
            Serial.println("connected");
            // alarmLevel = 0; //告警消除
            // 连接成功时订阅主题
           
            for (String topic : subTopicsArr) {
                mqttclient.subscribe(topic.c_str());
            }

            autoUploadFlag = 1;

        } else {

          Serial.print("failed, rc=");
          Serial.print(mqttclient.state());
          Serial.println(" try again in 3 seconds");
          // Wait 5 seconds before retrying
          delay(3000);
        }
    }
}

// 将电压转换为光强度（勒克斯），使用 10kΩ 电阻
float convertToLux(float voltage) {
    float resistorValue = 10000.0; // 假设使用 10kΩ 电阻
    float current = voltage / resistorValue; // 电流 = 电压 / 电阻
    float lux = current * 1000000.0; // 将电流 µA 转换为勒克斯
    return lux;
}

//SHT31温湿度
void i2c_master_init() {
    // I2C 配置
    static i2c_config_t conf;
    conf.mode = I2C_MODE_MASTER;
    conf.sda_io_num = IIC_SDA; // SDA
    conf.scl_io_num = IIC_SCL; // SCL
    conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
    conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
    conf.master.clk_speed = 100000; // 100 kHz

    // 初始化 I2C
    i2c_param_config(I2C_NUM_0, &conf);
    i2c_driver_install(I2C_NUM_0, conf.mode, 0, 0, 0);
}

void sht31_read(float *temperature, float *humidity) {
    uint8_t data[6];
    uint16_t temp_raw, hum_raw;

    // 发送测量命令
    uint8_t command[2] = {0x2C, 0x06}; // 发送命令
    i2c_master_write_to_device(I2C_NUM_0, SHT31_I2C_ADDRESS, command, sizeof(command), 1000 / portTICK_PERIOD_MS);

    // 等待测量完成
    vTaskDelay(500 / portTICK_PERIOD_MS);

    // 读取数据
    i2c_master_read_from_device(I2C_NUM_0, SHT31_I2C_ADDRESS, data, sizeof(data), 1000 / portTICK_PERIOD_MS);

    // 处理温度和湿度数据
    temp_raw = ((data[0] << 8) | data[1]);
    hum_raw = ((data[3] << 8) | data[4]);

    *humidity = (hum_raw * 100.0) / 65535.0; // 湿度计算
    *temperature = -45.0 + (175.0 * (temp_raw / 65535.0)); // 温度计算
}

// -------------------------------新增代码---------------------------------------------------

// 获取时间
void getTimeFromServer()
{
    String timeurl = "https://www.baidu.com";
    HTTPClient http;
    http.begin(timeurl);
    const char *headerKeys[] = {"Date"};
    http.collectHeaders(headerKeys, sizeof(headerKeys) / sizeof(headerKeys[0]));
    int httpCode = http.GET();
    Date = http.header("Date");
    Serial.println(Date);
    http.end();
    // delay(50); // 可以根据实际情况调整延时时间
}



void loop() {
    while(1);
}